package com.jfinal.weixin.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.weixin.entity.Music;
import org.jsoup.Jsoup;

import java.net.URLEncoder;
import java.util.ArrayList;

public class KuwoUtil {

    public static int total = 0;

    //搜索歌曲的静态方法
    public static ArrayList searchMusic(String searchName,int music_page)
    {
        ArrayList list = new ArrayList();

        try{
            //将搜索的文字内容进行url编码
            searchName = URLEncoder.encode(searchName, "UTF-8");
            String search_url = "http://www.kuwo.cn/api/www/search/searchMusicBykeyWord?key="+searchName+"&pn="+music_page+"&rn=10&httpsStatus=1&reqId=f4204631-2519-11ee-b40d-8f583c46c03e&plat=web_www&from=";
            //打开连接，并带上请求头%E5%90%91%E4%BA%91%E7%AB%AF
            String str = Jsoup.connect(search_url)
                .cookie("Hm_Iuvt_cdb524f42f0ce19b169b8072123a4727","XhT7N5bYk7nwCkiizmXTSY4awrfFZyPE")
                .header("Secret","06342e5bb4b18f50d50c8337e78df09447d8a1dceeb408ea0f0e6a97fec0477e02dbec3b")
                .referrer("http://www.kuwo.cn/search/list?key="+searchName)
                .ignoreContentType(true)
                .get().body().text();
            //打印测试一下请求返回的json数据
            //System.out.println(str);
            //解析json数据
            JSONObject jsonObject_1 = JSONObject.parseObject(str).getJSONObject("data");
            total = jsonObject_1.getInteger("total");

            JSONArray jsonArray = jsonObject_1.getJSONArray("list");
            for (int i=0;i<jsonArray.size();i++){

                //获取每一个list里的对象
                JSONObject jsonMusic = jsonArray.getJSONObject(i);

                Music music = new Music();
                music.setMusic_name(jsonMusic.getString("name"));
                music.setRid(jsonMusic.getString("rid"));
                music.setSinger(jsonMusic.getString("artist"));

                list.add(music);
            }


        }catch(Exception e){
            e.printStackTrace();
        }
        return list;

    }



    public static String getMp3Url(String rid){
        String mp3PlayUrl = "";
        try {
            String playUrl = "http://www.kuwo.cn/api/v1/www/music/playUrl?mid=" + rid + "&type=MP3&httpsStatus=1&reqId=bdf53ef1-ff56-11ed-a071-0f639e816d70";
            String str = Jsoup.connect(playUrl).ignoreContentType(true).get().body().text();
            JSONObject jsonObject = JSONObject.parseObject(str);
            if (jsonObject.getInteger("code") != -1) {
                mp3PlayUrl = jsonObject.getJSONObject("data").getString("url");
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        return mp3PlayUrl;
    }
}
